package com.jinzhi.jzapi.utils;

import com.jinzhi.jzweb.domain.vo.CertificateInfoVo;
import com.jinzhi.jzweb.domain.vo.InformationImportUserVo;
import com.jinzhi.jzweb.domain.vo.WorkExperinceVo;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.*;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.time.LocalDate;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;


public class PdfUtil {


    public static void main(String[] args) throws IOException {
        // 示例信息对象
        InformationImportUserVo informationImportUserVo = new InformationImportUserVo();
        informationImportUserVo.setName("214142");
        informationImportUserVo.setSex(1);
        informationImportUserVo.setBorn(LocalDate.now());
        informationImportUserVo.setEducation(4);
        informationImportUserVo.setMajor("计算机科学");
        informationImportUserVo.setCertificateType("0");
        informationImportUserVo.setIdcardNumber("123456789012345678");
        informationImportUserVo.setMobile("13800138000");
        informationImportUserVo.setPersonType(2);
        informationImportUserVo.setDeclaredLevel("初级");
        informationImportUserVo.setWorkUnit("某公司");
        informationImportUserVo.setDeclaredCareers("1");
        informationImportUserVo.setDeclaredSubject("0,1");
        informationImportUserVo.setPersonPhoto("https://jinzhiweiye.oss-cn-hangzhou.aliyuncs.com/2024/05/27/83937fba34604b719336dcdfc1986acdtmp_f00a7c6f75e60714e7597eee6774042e4457e55331f4977b.jpg");
        // 设置信息... (省略)

        // 填充PDF并生成新文件
        fillPdf(informationImportUserVo, "D:/upload/kaoshenshenbaobiao.pdf", "D:/git/kaoshenshenbaobiao.pdf");
    }


    public static void fillPdf(InformationImportUserVo informationImportUserVo, String inputPdfPath, String outputPdfPath) throws IOException {
        PDDocument document = PDDocument.load(new File(inputPdfPath));
        PDPage page = document.getPage(0);

        PDFont font = loadFontWithPostScriptName(document, "D:/git/fonts/simsun.ttf", "SimSun");


        try (PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {

            // 设置字体和颜色
            contentStream.setFont(font, 12);
            contentStream.setNonStrokingColor(Color.BLACK);
            // 填充文本信息
            contentStream.beginText();
            contentStream.newLineAtOffset(135, 670);  // 姓名位置
            contentStream.showText(informationImportUserVo.getName());
            contentStream.endText();

            contentStream.beginText();
            contentStream.newLineAtOffset(260, 670);  // 性别位置
            String sex = informationImportUserVo.getSex() == 1 ? "男" : "女";
            contentStream.showText(sex);
            contentStream.endText();
            contentStream.beginText();
            contentStream.newLineAtOffset(340, 670);  // 出生日期位置
            contentStream.showText(informationImportUserVo.getBorn().toString());
            contentStream.endText();

            String[] educationLevels = {"初中", "高中", "中专", "大专", "大学", "硕士", "博士"};
            String education = educationLevels[informationImportUserVo.getEducation() - 1];
            contentStream.beginText();
            contentStream.newLineAtOffset(135, 645);  // 学历位置
            contentStream.showText(education);
            contentStream.endText();

            contentStream.beginText();
            contentStream.newLineAtOffset(290, 645);  // 所学专业位置
            contentStream.showText(informationImportUserVo.getMajor());
            contentStream.endText();

            String certificateType = informationImportUserVo.getCertificateType().equals("0") ? "身份证" : "";
            contentStream.beginText();
            contentStream.newLineAtOffset(135, 620);  // 证件类型位置
            contentStream.showText(certificateType);
            contentStream.endText();

            contentStream.beginText();
            contentStream.newLineAtOffset(290, 620);  // 证件号码位置
            contentStream.showText(informationImportUserVo.getIdcardNumber());
            contentStream.endText();

            contentStream.beginText();
            contentStream.newLineAtOffset(135, 595);  // 手机号码位置
            contentStream.showText(informationImportUserVo.getMobile());
            contentStream.endText();

            int[] personTypeXOffset = {276, 310, 370};
            contentStream.beginText();
            contentStream.newLineAtOffset(personTypeXOffset[informationImportUserVo.getPersonType()], 600);  // 人员类别位置
            contentStream.showText("√");
            contentStream.endText();

            contentStream.beginText();
            contentStream.newLineAtOffset(135, 575);  // 工作单位位置
            contentStream.showText(informationImportUserVo.getWorkUnit());
            contentStream.endText();

            // 填充职业等级证书情况
        int yOffset = 532;
            int y = 4;
        int u=1;
            for (int x = 0; x < y; x++) {
                contentStream.beginText();
                contentStream.newLineAtOffset(125, yOffset);  // 序号位置
                contentStream.showText(String.valueOf(u));
                contentStream.endText();

                contentStream.beginText();
                contentStream.newLineAtOffset(155, yOffset);  // 工种位置
                contentStream.showText("vo.getCa");
                contentStream.endText();

                contentStream.beginText();
                contentStream.newLineAtOffset(250, yOffset);  // 等级位置
                contentStream.showText("吹季");
                contentStream.endText();

                contentStream.beginText();
                contentStream.newLineAtOffset(300, yOffset);  // 证书号位置
                contentStream.showText("vo.)");
                contentStream.endText();

                contentStream.beginText();
                contentStream.newLineAtOffset(440, yOffset);  // 发证日期位置
                contentStream.showText("vo.");
                contentStream.endText();

                yOffset -= 17;
                u++;
        }
//        String[] declaredSubjects = {"育婴员", "保育师", "养老护理员"};
//        String declaredSubject = declaredSubjects[informationImportUserVo.getDeclaredCareers()];
        contentStream.beginText();
        contentStream.newLineAtOffset(245, 462);  // 申报职业位置
        contentStream.showText(informationImportUserVo.getDeclaredCareers());
        contentStream.endText();

        contentStream.beginText();
        contentStream.newLineAtOffset(390, 462);  // 申报等级位置
        contentStream.showText(informationImportUserVo.getDeclaredLevel());
        contentStream.endText();

            // 定义一个映射来处理所有可能的科目索引及其对应的坐标
            Map<Integer, Integer> declaredSubjectXOffsetMap = new HashMap<>();
            declaredSubjectXOffsetMap.put(0, 145); // 对应你原来的位置 184
            declaredSubjectXOffsetMap.put(1, 194); // 对应你原来的位置 244
            declaredSubjectXOffsetMap.put(2, 240); // 对应你原来的位置 303
            // 假设 informationImportUserVo.getDeclaredSubject() 返回 "0,1,2"
            String declaredSubjectsString = informationImportUserVo.getDeclaredSubject();
            String[] declaredSubjectsArray = declaredSubjectsString.split(",");

            for (String subject : declaredSubjectsArray) {
                int index = Integer.parseInt(subject.trim());
                if (declaredSubjectXOffsetMap.containsKey(index)) {
                    contentStream.beginText();
                    contentStream.newLineAtOffset(declaredSubjectXOffsetMap.get(index), 442);  // 申报科目位置
                    contentStream.showText("√");
                    contentStream.endText();
                } else {
                    throw new IllegalArgumentException("Invalid declared subject index: " + subject);
                }
            }


        yOffset = 385;
            for (int x = 0; x < y; x++) {
                contentStream.setFont(font, 7);
                contentStream.beginText();
                contentStream.newLineAtOffset(70, yOffset);  // 起止年月位置
                contentStream.showText("2024/05/02"+ "-" + "2024/05/02");
                contentStream.endText();

                contentStream.setFont(font, 10);
                contentStream.beginText();
                contentStream.newLineAtOffset(155, yOffset);  // 工作单位位置
                contentStream.showText("vo.getWorkUnit()");
                contentStream.endText();

                contentStream.beginText();
                contentStream.newLineAtOffset(315, yOffset);  // 工作岗位位置
                contentStream.showText("测试测试测");
                contentStream.endText();

                contentStream.beginText();
                contentStream.newLineAtOffset(375, yOffset);  // 单位联系人位置
                contentStream.showText("vo.getC");
                contentStream.endText();

                contentStream.beginText();
                contentStream.newLineAtOffset(448, yOffset);  // 联系电话位置
                contentStream.showText("12313132321");
                contentStream.endText();

                yOffset -= 20;
            }

            if (informationImportUserVo.getPersonPhoto() != null) {
                String imageUrl = informationImportUserVo.getPersonPhoto();
                URL url = new URL(imageUrl);
                BufferedImage img = ImageIO.read(url);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(img, "jpg", baos); // 假设图片为JPEG格式，根据实际情况调整
                byte[] imageBytes = baos.toByteArray(); // 从 ByteArrayOutputStream 获取字节数组

                PDImageXObject pdImage = PDImageXObject.createFromByteArray(document, imageBytes, "");

                contentStream.drawImage(pdImage, 435, 575, 90, 100);  // 照片位置
        }
//
            contentStream.close();
            document.save(outputPdfPath);
            document.close();
        } catch (IOException e) {
            System.err.println("创建内容流时出错：" + e.getMessage());
            e.printStackTrace();
        }




//        List<CertificateInfoVo> certificateInfoVos = informationImportUserVo.getCertificateInfoVos();
//        if (!certificateInfoVos.isEmpty()) {
//            List<CertificateInfoVo> collect = certificateInfoVos.stream().filter(Objects::nonNull).limit(4).collect(Collectors.toList());
//            int x = 1;
//            for (CertificateInfoVo vo : collect) {
//                contentStream.beginText();
//                contentStream.newLineAtOffset(125, yOffset); // 序号位置
//                contentStream.showText(String.valueOf(x));
//                contentStream.endText();
//
//                contentStream.beginText();
//                contentStream.newLineAtOffset(155, yOffset);  // 工种位置
//                contentStream.showText("vo.getCareer()");
//                contentStream.endText();
//
//                contentStream.beginText();
//                 contentStream.newLineAtOffset(250, yOffset); // 等级位置
//                contentStream.showText("vo.getLevel()");
//                contentStream.endText();
//
//                contentStream.beginText();
//                 contentStream.newLineAtOffset(300, yOffset);  // 证书号位置
//                contentStream.showText("vo.getNumber()");
//                contentStream.endText();
//
//                contentStream.beginText();
//                 contentStream.newLineAtOffset(440, yOffset);  // 发证日期位置
//                contentStream.showText("vo.getCertificateTime().toString()");
//                contentStream.endText();
//
//                yOffset -= 20;
//                x++;
//            }
//        }

//
//
//
//        String[] declaredSubjects = {"育婴员", "保育师", "养老护理员"};
//        String declaredSubject = declaredSubjects[informationImportUserVo.getDeclaredCareers()];
//        contentStream.beginText();
//        contentStream.newLineAtOffset(160, 420);  // 申报职业位置
//        contentStream.showText(declaredSubject);
//        contentStream.endText();
//
//        contentStream.beginText();
//        contentStream.newLineAtOffset(320, 420);  // 申报等级位置
//        contentStream.showText(informationImportUserVo.getDeclaredLevel().toString());
//        contentStream.endText();
//
//        int[] declaredSubjectXOffset = {135, 230, 320};
//        contentStream.beginText();
//        contentStream.newLineAtOffset(declaredSubjectXOffset[informationImportUserVo.getDeclaredSubject()], 400);  // 申报科目位置
//        contentStream.showText("√");
//        contentStream.endText();
//
//        yOffset = 370;
//        List<WorkExperinceVo> experinceVos = informationImportUserVo.getExperinceVos();
//        if (!experinceVos.isEmpty()) {
//            List<WorkExperinceVo> collect = experinceVos.stream().filter(Objects::nonNull).limit(4).collect(Collectors.toList());
//            for (WorkExperinceVo vo : collect) {
//                contentStream.setFont(font, 7);
//                contentStream.beginText();
//                contentStream.newLineAtOffset(70, yOffset);  // 起止年月位置
//                contentStream.showText(vo.getStartTime() + "-" + vo.getEndTime());
//                contentStream.endText();
//                contentStream.setFont(font, 7);
//                contentStream.beginText();
//                contentStream.newLineAtOffset(155, yOffset);  // 工作单位位置
//                contentStream.showText(vo.getWorkUnit());
//                contentStream.endText();
//
//                contentStream.beginText();
//                contentStream.newLineAtOffset(315, yOffset);  // 工作岗位位置
//                contentStream.showText(vo.getJob().substring(0, Math.min(vo.getJob().length(), 5)));
//                contentStream.endText();
//
//                contentStream.beginText();
//                 contentStream.newLineAtOffset(375, yOffset);  // 单位联系人位置
//                contentStream.showText(vo.getContact());
//                contentStream.endText();
//
//                contentStream.beginText();
//                contentStream.newLineAtOffset(448, yOffset);    // 联系电话位置
//                contentStream.showText(vo.getContactMobile());
//                contentStream.endText();
//
//                yOffset -= 20;
//            }
//        }
//
//        // 插入照片
//        if (informationImportUserVo.getPersonPhoto() != null) {
//            String imageUrl = informationImportUserVo.getPersonPhoto();
//            URL url = new URL(imageUrl);
//            BufferedImage img = ImageIO.read(url);
//            PDImageXObject pdImage = PDImageXObject.createFromFileByContent(new File(imageUrl), document);
//
//            contentStream.drawImage(pdImage, 500, 680, 100, 100);  // 照片位置
//        }
//

    }

    // 加载字体并手动设置PostScript名称
    private static PDFont loadFontWithPostScriptName(PDDocument document, String fontFilePath, String postScriptName) throws IOException {
        PDFont font = PDType0Font.load(document, new File(fontFilePath));
        PDFontDescriptor fontDescriptor = font.getFontDescriptor();
        fontDescriptor.setFontName(postScriptName);
        return font;
    }

}


